# Tiny QA PowerShell 快速启动脚本
# 使用方法: 右键点击此文件 -> "使用PowerShell运行"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Tiny QA - PowerShell 快速启动" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan

# 检查是否在项目根目录
if (-not (Test-Path "app.py")) {
    Write-Host "❌ 错误: 请在项目根目录运行此脚本" -ForegroundColor Red
    Read-Host "按任意键退出"
    exit 1
}

# 检查虚拟环境
if (-not (Test-Path "env")) {
    Write-Host "⚠️ 虚拟环境不存在，正在创建..." -ForegroundColor Yellow
    & python -m venv env
    if ($LASTEXITCODE -ne 0) {
        Write-Host "❌ 创建虚拟环境失败" -ForegroundColor Red
        Read-Host "按任意键退出"
        exit 1
    }
}

# 激活虚拟环境
Write-Host "🔄 激活虚拟环境..." -ForegroundColor Green
& "env\Scripts\Activate.ps1"

# 检查依赖
Write-Host "📚 检查依赖..." -ForegroundColor Green
try {
    & python -c "import flask, chromadb, sentence_transformers" 2>$null
    if ($LASTEXITCODE -ne 0) {
        throw "依赖不完整"
    }
} catch {
    Write-Host "⚠️ 依赖不完整，正在安装..." -ForegroundColor Yellow
    & pip install -r requirements.txt
    if ($LASTEXITCODE -ne 0) {
        Write-Host "❌ 安装依赖失败" -ForegroundColor Red
        Read-Host "按任意键退出"
        exit 1
    }
}

# 创建必要目录
Write-Host "📁 创建必要目录..." -ForegroundColor Green
if (-not (Test-Path "data\database")) { New-Item -ItemType Directory -Path "data\database" -Force | Out-Null }
if (-not (Test-Path "data\documents")) { New-Item -ItemType Directory -Path "data\documents" -Force | Out-Null }
if (-not (Test-Path "data\vectors")) { New-Item -ItemType Directory -Path "data\vectors" -Force | Out-Null }
if (-not (Test-Path "logs")) { New-Item -ItemType Directory -Path "logs" -Force | Out-Null }

# 检查Ollama
Write-Host "🤖 检查Ollama..." -ForegroundColor Green
try {
    & ollama --version 2>$null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✅ Ollama已安装" -ForegroundColor Green
    } else {
        Write-Host "⚠️ 未找到Ollama，将使用默认配置" -ForegroundColor Yellow
    }
} catch {
    Write-Host "⚠️ 未找到Ollama，将使用默认配置" -ForegroundColor Yellow
}

# 获取端口配置
$port = 5002
try {
    $config = Get-Content "config/settings.yaml" -Raw | ConvertFrom-Yaml
    $port = $config.app.port
} catch {
    Write-Host "⚠️ 无法读取配置文件，使用默认端口5002" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "🚀 启动 Tiny QA 服务..." -ForegroundColor Green
Write-Host "访问地址: http://localhost:$port" -ForegroundColor Cyan
Write-Host "API地址: http://localhost:$port/api" -ForegroundColor Cyan
Write-Host "按 Ctrl+C 停止服务" -ForegroundColor Yellow
Write-Host ""

# 启动应用
& python app.py

Read-Host "按任意键退出" 